package cn.shoukaiseki.sjf4j.jackson;


import cn.shoukaiseki.sjf4j.JsonException;
import cn.shoukaiseki.sjf4j.Sjf4j;
import cn.shoukaiseki.sjf4j.node.TreeNode;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * jackson 的 sjf4j 实现类
 * <br>
 * cn.shoukaiseki.sjf4j.impl.JacksonImpl
 * <br>
 * @author shoukaiseki
 * 主页 https://gitee.com/shoukaiseki/<br>
 * E-mail jiang28555@qq.com<br>
 * @date 2024-05-22 17:45:12<br>
 */
public class JacksonImpl implements Sjf4j {

    private ObjectMapper objectMapper=new ObjectMapper();

    @Override
    public String toJsonString(Object obj)  {
        try {
            return objectMapper.writeValueAsString(obj);
        }catch (Throwable t){
            throw new JsonException(t);
        }
    }

    @Override
    public <T> T jsonToObj(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json,clazz);
        }catch (Throwable t){
            throw new JsonException(t);
        }
    }

    @Override
    public TreeNode jsonToObj(String json) {
        try {
            JsonNode jsonNode = objectMapper.readValue(json, JsonNode.class);
            return JacksonTreeNode.convert(jsonNode);
        } catch (Throwable t) {
            throw new JsonException(t);
        }
    }

    @Override
    public TreeNode jsonToArrayNode(String json) {
        try {
            ArrayNode jsonNode = objectMapper.readValue(json, ArrayNode.class);
            return new JacksonArrayNode(jsonNode);
        } catch (Throwable t) {
            throw new JsonException(t);
        }
    }

    @Override
    public TreeNode jsonToObjectNode(String json) {
        try {
            ObjectNode jsonNode = objectMapper.readValue(json, ObjectNode.class);
            return new JacksonObjectNode(jsonNode);
        } catch (Throwable t) {
            throw new JsonException(t);
        }
    }
}
